from rest_framework import serializers
from .models import *


class AdvSer(serializers.ModelSerializer):
    class Meta:
        model = AdvContent
        fields = "__all__"


class CategorySer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = "__all__"


class Category2Ser(serializers.ModelSerializer):
    # 自定义一个字段 来表述  二级分类下的所有3级分类
    category3_list = serializers.SerializerMethodField()

    def get_category3_list(self, cate2):
        queryset = Category.objects.filter(parent_id=cate2.id)
        return CategorySer(queryset, many=True).data

    class Meta:
        model = Category
        fields = "__all__"


class ChannelSer(serializers.ModelSerializer):
    category1_list = serializers.SerializerMethodField()

    category2_list = serializers.SerializerMethodField()

    # category_set = CategorySer()
    # 获取 频道下所有的一级分类
    def get_category1_list(self, channel):
        # 根据 channel 对象 去查询 包含的所有分类
        queryset = Category.objects.filter(channel_id=channel.id, level=1)
        return CategorySer(queryset, many=True).data

    # 获取频道下所有的二级分类
    def get_category2_list(self, channel):
        # 根据 channel 对象 去查询 包含的所有分类
        queryset = Category.objects.filter(channel_id=channel.id, level=2)
        return Category2Ser(queryset, many=True).data

    class Meta:
        model = Channel
        fields = "__all__"


# 商品列表的序列化
class GoodsListSer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = ["id", "name", "price", "pic","comments"]


# 商品详细的序列化
class GoodsDetailSer(serializers.ModelSerializer):
    category1 = serializers.SerializerMethodField()
    category2 = serializers.SerializerMethodField()
    category3 = serializers.SerializerMethodField()

    def get_category1(self, goods):
        cate1 = Category.objects.get(id=goods.category1)
        return {"name": cate1.name, "id": cate1.id}

    def get_category2(self, goods):
        cate2 = Category.objects.get(id=goods.category2)
        return {"name": cate2.name, "id": cate2.id}

    def get_category3(self, goods):
        cate3 = Category.objects.get(id=goods.category3)
        return {"name": cate3.name, "id": cate3.id}

    class Meta:
        model = Goods
        fields = "__all__"


# 创建一个 分类商品组合序列化

class CategoryGoodsSer(serializers.ModelSerializer):
    # 定义一个字段
    goods_list = serializers.SerializerMethodField()

    def get_goods_list(self, cate):
        queryset = Goods.objects.filter(category1=cate.id)
        return GoodsListSer(queryset, many=True).data

    class Meta:
        model = Category
        fields = "__all__"


class SpecifySer(serializers.ModelSerializer):
    class Meta:
        model = Specify
        fields = "__all__"
